var Shares = require('gameshare');
var GameObject = Shares.GameObject;
var GameEvent = Shares.GameEvent;
var GameConst = Shares.GameConst;

cc.Class({
    extends: cc.Component,

    properties: {
        objectType: {
            type:GameObject,
            default: GameObject.Star
        },
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},
    onLoad: function () {
        this.halfsize = GameConst.halfsize;
        this.size = GameConst.size;
        this.width = GameConst.width;
        this.height = GameConst.height;
    },

    onDestroy () {

    },

    start () {
        this.alineToLines();
        this.screenPos = this.node.convertToWorldSpaceAR(cc.v2(0, 0));
        this.refresh();
    },

    alineToLines: function(){
        var x = this.node.x - this.halfsize;
        x = Math.floor(x/this.size)*(this.size) + this.halfsize;
        var y = this.node.y - this.halfsize;
        y = Math.floor(y/this.size)*(this.size) + this.halfsize;
        this.node.x = x;
        this.node.y = y;
    },

    refresh(){
       

    },

    setData: function(data){
        this.node.position = data.position;
        this.refresh();
    },
    
    toData: function(){
        var data = {
            objectType: this.objectType,
            position: this.node.position,
        }

        return data;
    },

    isInRect: function (pos) {
        var posscreen = this.screenPos;
        if (pos.x < posscreen.x + this.halfsize &&
            pos.x > posscreen.x - this.halfsize &&
            pos.y < posscreen.y + this.halfsize &&
            pos.y > posscreen.y - this.halfsize) {
            return true;
        }

        return false
    },

    update: function (dt) {
        if (cc.zsb && cc.zsb.player) {
            var player = cc.zsb.player;
            if (player && player.isPause == false) {
                var collide = false;
                var playerScreenPos = player.getScreenPos();
                if (this.isInRect(playerScreenPos)) {
                    collide = true
                }

                if (collide) {
                    cc.systemEvent.emit(GameEvent.GetStar, this.node);
                }
            }
        }
    },
});
